#!/bin/bash
# simplemq-cpp 编译脚本
# Optional Command Arguments:
#        ONLYBUILD 不执行 cmake 创建工程只编译版本
# Optional Environment Variables: 
#        BUILD_TYPE 编译版本类型(DEBUG|RELEASE),默认 DEBUG
#        BUILD_PRJ 为 ON 时编译版本
#        RELEASE_PRJ 为 ON 时编译并 release 版本
# Xcode 编译方式
# G=Xcode ./gnu_build.sh

#字符串转大写
#参数1：字符串
function string_toupper()
{
    echo $1 | tr '[a-z]' '[A-Z]'
}
#字符串转小写
#参数1：字符串
function string_lower()
{
    echo $1 | tr '[A-Z]' '[a-z]'
}
sh_folder=$(cd "$(dirname $0)"; pwd -P)
folder_name=$(basename $sh_folder) 
# 定义编译的版本类型(debug|release)
build_type=release
[[ "$(string_lower $BUILD_TYPE)" =~ debug|release ]] && build_type=$(string_lower ${BUILD_TYPE})

# 是否编译测试和工具程序
build_test=ON

# 默认cmake -G 生成的工程文件类型
[ -z "$G" ] && G="Eclipse CDT4 - Unix Makefiles"

BUILD_PRJ=ON
echo build_type=$build_type

# 执行 cmake 创建工程
create_prj=ON
while [[ $# -gt 0 ]]
do
# 转大写
key=$(string_toupper ${1})
case $key in
ONLYBUILD)
	create_prj=OFF;BUILD_PRJ=ON;shift;;
*) shift;;
esac
done

machine=$(g++ -dumpmachine)
gcc_version=$(g++ -dumpversion) 

so_suffix=so
[[ "$machine" =~ .+darwin.+ ]] && so_suffix=dylib

# 安装路径
install_prefix=$sh_folder/release/simplemq-$machine

# 编译路径
prj_folder=$sh_folder/../simplemq-$machine.prj
[[ "$(string_toupper ${RELEASE_PRJ})" =~ ON ]] && prj_folder=$sh_folder/build/simplemq-$machine

echo =========================================================================
echo       Configuration: simplemq $machine:$build_type
echo     Build Directory: $prj_folder
echo   Install Directory: $install_prefix
echo =========================================================================

if [[ "$(string_toupper ${create_prj})" =~ ON ]]
then
	[ -d $prj_folder ] && rm -fr $prj_folder
	mkdir -p $prj_folder || exit 

	pushd $prj_folder || exit

	# MinGW编译时要通过CC,CXX指定编译器
	# 参见: https://blog.csdn.net/10km/article/details/123542518
	[[ "$(uname -s)" =~ (MINGW|MSYS|CYGWIN) ]] && export  CC=$(which gcc) && export CXX=$(which g++)
	# conan 安装依赖库
	conan install -s build_type=${build_type^} \
		--requires common_source_cpp/1.0.1 \
		--requires paho-mqtt-cpp/1.2.0 \
		--requires cpp_redis/master \
		-s compiler=gcc \
		-s compiler.version=${gcc_version:0:3} \
		-s compiler.libcxx=libstdc++11 \
		-g CMakeDeps \
		-g CMakeToolchain \
		$CONAN_REMOTE_REPO \
		--build missing || exit

	echo "creating Project for $machine ..."
	cmake "$sh_folder" -G "$G" -DCMAKE_BUILD_TYPE=$(string_toupper $build_type) \
		-DCMAKE_TOOLCHAIN_FILE=./conan_toolchain.cmake \
		-DCMAKE_INSTALL_PREFIX=$install_prefix || exit
		
else
	pushd $prj_folder || exit
fi

if [[ "$(string_toupper ${RELEASE_PRJ})" =~ ON ]] || [[ "${BUILD_PRJ})" =~ ON ]]
then
	cmake --build . --config $build_type -- -j 8 || exit 
fi

popd

